package org.hh.netty.client;

import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import lombok.SneakyThrows;
import org.hh.netty.utils.IpUtil;
import org.hh.netty.utils.SysUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class StudentConnection implements Runnable {

    Label label;

    public StudentConnection(Label label) {
        this.label = label;
    }

    @Override
    public void run() {
        String ip = searchTeacherIp();
        new StudentServer(ip).startClientServer();
    }

    /**
     * 查找IP
     * @return
     */
    @SneakyThrows
    private String searchTeacherIp(){
        String ip = null;
        String gateway = IpUtil.getLocalIp4Address().get().getHostAddress();
        gateway = gateway.substring(0, gateway.lastIndexOf(".")+1);

        while (ip==null){
            for (int i = 1; i < 255; i++) {
                String inetAddress = gateway + i;
                Socket socket = new Socket();
                try {
                    setMsg("正在查找教师机("+inetAddress+")...");
                    socket.connect(new InetSocketAddress(inetAddress, 8888), 100);
                    ip = inetAddress;
                    System.out.println("找到教师机："+ip);
                    break;
                } catch (IOException e) {
                }
            }
            if (ip==null) {
                setMsg("教师机未开启，请联系管理员");
                Thread.sleep(5000);
            }
        }
        return ip;
    }

    /**
     * 设置提示信息
     * @param msg
     */
    private void setMsg(String msg){
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                label.setText(msg);
            }
        });
    }
}
